/**
 * 上海中赢金融信息服务有限公司
 * Copyright (c) 2017-2027 Chinazyjr,Inc.All Rights Reserved.
 */
package com.sys.midware.rdb.handler;

import com.sys.midware.rdb.datasource.BDataSource;
import com.sys.midware.rdb.exception.RDBException;

/**
 * 
 * <b>ClassName：</b> HBaseDBFactory <br/>
 * <b>Description：</b> TODO <br/>
 * <b>@author：</b> mobing <br/>
 * <b>@date：</b> 2015年10月26日 下午3:40:39 <br/>
 * <b>@version: </b> <br/>
 */
public class RDBFactory {
    private static RDBFactory instance;

    private RDBFactory() {
    }

    private BDataSource pool;

    public void checkDBAvailable() throws Exception {
        // 实例化成功，表示连接正常
    }

    /**
     * 获取单例工厂
     * 
     * @return
     * @throws Exception
     */
    public static RDBFactory getInstance() throws Exception {
        if (instance != null)
            return instance;

        synchronized (RDBFactory.class) {
            if (instance == null) {
                instance = new RDBFactory();
                instance.init(null, null);
            }

            return instance;
        }
    }

    /**
     * 获取单例工厂
     * 
     * @return
     * @throws Exception
     */
    public static RDBFactory getInstance(String configPath) throws Exception {
        if (instance != null)
            return instance;

        synchronized (RDBFactory.class) {
            if (instance == null) {
                instance = new RDBFactory();
                instance.init(configPath, null);
            }

            return instance;
        }
    }

    /**
     * 获取单例工厂
     * 
     * @return
     * @throws Exception
     */
    public static RDBFactory getInstance(String configPath, String nodeKey) throws Exception {
        if (instance != null)
            return instance;

        synchronized (RDBFactory.class) {
            if (instance == null) {
                instance = new RDBFactory();
                instance.init(configPath, nodeKey);
            }

            return instance;
        }
    }

    /**
     * 实例化DB连接池
     * 
     * @throws Exception
     */
    private void init(String configPath, String nodeKey) throws RDBException {
        try {

            pool = new BDataSource(configPath, nodeKey);
            pool.init();
        } catch (Exception e) {
            pool = null;
            throw new RDBException("Error happened while initializing the DB connection pool.", e);
        }
    }

    public IRDBHandlerMyBatis getRDBHandler4MyBatis() throws Exception {

        return new RDBHandlerMyBatis(pool);
    }

    public IRDBHandlerMyBatis getRDBHandler4MyBatis(String mybatisConfig) throws Exception {

        return new RDBHandlerMyBatis(pool, mybatisConfig);
    }

    
    public IRDBHandlerJDBC getRDBHandler4JDBC() throws Exception {

        return new RDBHandlerJDBC(pool);
    }
    
    public void shutdown() throws Exception {
        if (pool != null) {
            pool.close();
            pool = null;
        }
    }

}
